const db = require('../../db/db.js')
const { getSqlData } = require('../../utils/sqlUtils.js')

// 添加店铺
exports.addStore = (request, response) => {
  let data = request.body;

  // 验证输入数据
  if (!data?.name || !data?.logo) {
    return response.send({
      code: 400,
      message: '缺少店铺名称、logo！'
    });
  }
  // 检查店铺名称是否已存在
  let checkSql = `SELECT * FROM store WHERE name = ?`;
  db.query(checkSql, [data.name], (err, result) => {
    if (err) {
      return response.send(err);
    }
    if (result.length > 0) {
      return response.send({
        code: 404,
        message: '店铺名称已存在！',
      });
    } else {
      // 插入新店铺
      let sql = `INSERT INTO store SET ?`;
      db.query(sql, data, (err, result) => {
        if (err) {
          return response.send(err);
        }
        response.send({ code: 200, message: '店铺添加成功！', data: data });
      });
    }
  });
};

// 查询店铺
exports.getStore = (request, response) => {
  let id = request.params?.id;
  let keyword = request.query?.keyword;
  let is_recommend = request.query?.is_recommend;
  let is_new = request.query?.is_new;
  let is_hot = request.query?.is_hot;
  let is_delete = request.query?.is_delete;


  // 分页参数
  let page = parseInt(request.query?.page) || 1; // 默认第1页
  let pageSize = parseInt(request.query?.page_size) || 20; // 默认每页20条记录

  let conditions = [];
  let queryParams = [];

  if (keyword) {
    conditions.push('store_name LIKE ?');
    queryParams.push(`%${keyword}%`);
  }

  // 添加查询条件
  if (id) {
    conditions.push('id = ?');
    queryParams.push(id);
  }

  if (is_recommend) {
    conditions.push('is_recommend = ?');
    queryParams.push(is_recommend);
  }
  if (is_new) {
    conditions.push('is_new = ?');
    queryParams.push(is_new);
  }
  if (is_hot) {
    conditions.push('is_hot = ?');
    queryParams.push(is_hot);
  }
  
  if (is_delete) {
    conditions.push('is_delete = ?');
    queryParams.push(is_delete);
  }


  let whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
  let offset = (page - 1) * pageSize;

  // SQL 查询，包括分页
  let sql = `SELECT * FROM store ${whereClause} LIMIT ? OFFSET ?`;
  queryParams.push(pageSize, offset);

  // 查询数据和总条数
  let countSql = `SELECT COUNT(*) AS total FROM store ${whereClause}`;

  db.query(sql, queryParams, (err, results) => {
    if (err) {
      return response.send({
        code: 500,
        message: '查询失败！',
        error: err
      });
    }

    db.query(countSql, queryParams.slice(0, -2), (err, countResult) => {
      if (err) {
        return response.send({
          code: 500,
          message: '总条数查询失败！',
          error: err
        });
      }

      let total = countResult[0].total;
      let last_page = Math.ceil(total / pageSize);

      response.send({
        code: 200,
        message: '查询成功！',
        current_page: page,
        last_page: last_page,
        total: total,
        page_size: pageSize,
        data: results
      });
    });
  });
};


// 修改店铺
exports.setStore = (request, response) => {
  const { id } = request.params;
  const data = request.body;

  // 验证输入数据
  if (!id) {
    return response.send({
      code: 400,
      message: '店铺ID不能为空。',
    });
  }

  // 检查店铺是否存在
  let checkSql = `SELECT * FROM store WHERE id = ?`;
  db.query(checkSql, [id], (err, result) => {
    if (err) {
      return response.send(err);
    }
    if (result.length === 0) {
      return response.send({
        code: 404,
        message: '店铺不存在！'
      });
    } else {
      // 更新店铺
      let updateSql = `UPDATE store SET ? WHERE id = ?`;
      db.query(updateSql, [data, id], (err, result) => {
        if (err) {
          return response.send(err);
        }
        response.send({ code: 200, message: '店铺更新成功！', data: data });
      });
    }
  });
};
